/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "auth_crypt.h"
#include <cstring>
#include "node/crypto/hmac.h"

AuthCrypt::AuthCrypt(void)
    : key_()
    , send_i_(0)
    , send_j_(0)
    , recv_i_(0)
    , recv_j_(0)
    , inited_(false)
{

}

AuthCrypt::~AuthCrypt(void)
{

}

void AuthCrypt::Init(void)
{
    send_i_ = send_j_ = recv_i_ = recv_j_ = 0;
    inited_ = true;
}

void AuthCrypt::SetKey(::std::uint8_t *key, ::std::size_t size)
{
    key_.resize(size);
    ::std::copy(key, key + size, key_.begin());
}

void AuthCrypt::DecryptRecv(::std::uint8_t *data, ::std::size_t size)
{
    if (!inited_) { return; }
    if (size < CRYPTED_RECV_LEN) { return; }

    for (::std::size_t t = 0; t < CRYPTED_RECV_LEN; t++)
    {
        recv_i_ %= key_.size();
        ::std::uint8_t x = (data[t] - recv_j_) ^ key_[recv_i_];
        ++recv_i_;
        recv_j_ = data[t];
        data[t] = x;
    }
}

void AuthCrypt::EncryptSend(::std::uint8_t *data, ::std::size_t size)
{
    if (!inited_) { return; }
    if (size < CRYPTED_SEND_LEN) { return; }

    for (::std::size_t t = 0; t < CRYPTED_SEND_LEN; t++)
    {
        send_i_ %= key_.size();
        ::std::uint8_t x = (data[t] ^ key_[send_i_]) + send_j_;
        ++send_i_;
        data[t] = send_j_ = x;
    }
}

void AuthCrypt::GenerateKey(::std::uint8_t *key, ::node::crypto::BigNumber *bn)
{
    ::node::crypto::HmacHash hash;
    hash.UpdateBigNumber(bn);
    hash.Finalize();
    memcpy(key, hash.GetDigest(), SHA_DIGEST_LENGTH);
}